package com.qdaily.ui.ui.views;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.qdaily.supportlibrary.util.ImageUtil;
import com.qdaily.ui.MainActivity;
import com.qdaily.ui.QDBaseActivity;
import com.qdaily.ui.R;
import com.qdaily.ui.data.Constants;
import com.qdaily.ui.data.UserInformation;
import com.qdaily.ui.net.QDEnum;
import com.qdaily.ui.net.model.HomeLeftSidebarFeed;
import com.qdaily.ui.ui.LoginActivity;
import com.qdaily.ui.ui.SearchActivity;
import com.qdaily.ui.ui.SettingActivity;
import com.qdaily.ui.ui.WebViewActivity;
import com.qdaily.ui.ui.fragment.CategoryFragment;
import com.qdaily.ui.ui.fragment.MainFragment;
import com.qdaily.ui.ui.fragment.MyDynamicFragment;
import com.qdaily.ui.ui.fragment.PersonalCenterFragment;
import com.qdaily.ui.ui.views.radar.SpiderWebChart;
import com.qdaily.ui.ui.views.radar.TitleValueEntity;
import com.qdaily.ui.util.BusProvider;
import com.squareup.otto.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 侧边栏，列表。
 * Created with IntelliJ IDEA.
 * User: Felix
 * Date: 4/21/15
 * Time: 17:49
 * QQ:74104
 * Email:lovejiuwei@gmail.com
 */
public class SidebarController extends LinearLayout implements View.OnClickListener, ImageLoadingListener {

    private View headerView = null;
    private SpiderWebChart spiderWebChartard = null;
    private ImageView imageViewLeftSidebarAvatar;
    private TextView textViewLeftSidebarUser;
    private TextView textViewLeftSidebarUserDes;
    private MainActivity mContext;
    private View footView = null;
    private TextView textViewLeftSidebarSettings;
    private TextView textViewLeftSidebarAbout;
    private TextView textViewLeftSidebarSearch;
    private ImageButton imageButtonLeftSidebarAboutSina;
    //侧边栏下载图片后选中、为选中集合。
    private HashMap<String, Drawable> viewDrawableSelect = new HashMap<>();
    //本地缓存
    private View homePage = null;//主页,常驻
    private View institute = null;//研究院，常驻
    private View myFavorite = null;//我的收藏，登陆以后
    private View myDyna = null;//我的动态，登陆以后

    //通过hander转发点击事件
    private final int LOCAL_ITEM_TYPE_HOME = 0x1;
    private final int LOCAL_ITEM_TYPE_INSTITUTE = 0x2;
    private final int LOCAL_ITEM_TYPE_MYFAVORITE = 0x3;
    private final int LOCAL_ITEM_TYPE_MYDYNA = 0x4;
    private final int NET_ITEM_TYPE = 0x5;

    private View selectView;

    public SidebarController(Context context) {
        this(context, null);
    }

    public SidebarController(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SidebarController(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        this.mContext = (MainActivity) context;
        initViewRes();

        readCacheDisplayUserInfo(mContext.getUserInformationManager().getUserInformation());
    }

    private void initViewRes() {
        headerView = LayoutInflater.from(getContext()).inflate(R.layout.view_left_sidebar_headview, null);
        spiderWebChartard = (SpiderWebChart) headerView.findViewById(R.id.spiderWebChartard);

        spiderWebChartard.setiSpiderWeChartOnClikc(new SpiderWebChart.ISpiderWeChartOnClikc() {
            @Override
            public void onClick(TitleValueEntity titleValueEntity) {
                if (TextUtils.isEmpty(titleValueEntity.getTitle()) || titleValueEntity.getId() == 0) {
                    return;
                }
                CategoryFragment.CategoryDataObj categoryDataObj = new CategoryFragment.CategoryDataObj().
                        setCategoryFragmetType(QDEnum.CategoryFragmentEnum.SPIDERWEBCHART)
                        .setCategoryId(titleValueEntity.getId())
                        .setIsTitlebarLeftBtnVisiable(false)
                        .setTitleText(titleValueEntity.getTitle());
                enterCategoryFragment(categoryDataObj);
                mContext.closeDrawers();
            }
        });

        imageViewLeftSidebarAvatar = (ImageView) headerView.findViewById(R.id.imageViewLeftSidebarAvatar);
        textViewLeftSidebarUser = (TextView) headerView.findViewById(R.id.textViewLeftSidebarUser);
        textViewLeftSidebarUserDes = (TextView) headerView.findViewById(R.id.textViewLeftSidebarUserDes);
        imageViewLeftSidebarAvatar.setOnClickListener(this);
        textViewLeftSidebarUser.setOnClickListener(this);
        textViewLeftSidebarUserDes.setOnClickListener(this);
        //the add the headerview first
        this.addView(headerView);

        homePage = LayoutInflater.from(getContext()).inflate(R.layout.view_left_sidebar_item, null);
        ((ImageView) homePage.findViewById(R.id.imageViewLeftSidebarItemAvatar)).setImageResource(R.drawable.icon_sidebar_main_selector);
        ((TextView) homePage.findViewById(R.id.textViewSidebarItemTitle)).setText(R.string.homepage);
        homePage.setTag(LOCAL_ITEM_TYPE_HOME);
        homePage.setOnClickListener(this);
        homePage.setSelected(true);
        selectView = homePage;
        this.addView(homePage);

        institute = LayoutInflater.from(getContext()).inflate(R.layout.view_left_sidebar_item, null);
        ((TextView) institute.findViewById(R.id.textViewSidebarItemTitle)).setText(R.string.institute_of_living);
        ((ImageView) institute.findViewById(R.id.imageViewLeftSidebarItemAvatar)).setImageResource(R.drawable.icon_sidebar_research_selector);
        institute.setTag(LOCAL_ITEM_TYPE_INSTITUTE);
        institute.setOnClickListener(this);
        this.addView(institute);

        myFavorite = LayoutInflater.from(getContext()).inflate(R.layout.view_left_sidebar_item, null);
        ((TextView) myFavorite.findViewById(R.id.textViewSidebarItemTitle)).setText(R.string.my_favorite);
        ((ImageView) myFavorite.findViewById(R.id.imageViewLeftSidebarItemAvatar)).setImageResource(R.drawable.icon_sidebar_fav_selector);
        myFavorite.setTag(LOCAL_ITEM_TYPE_MYFAVORITE);
        myFavorite.setOnClickListener(this);
        this.addView(myFavorite);
    }

    public void updateRadar(List<TitleValueEntity> data) {
        spiderWebChartard.setData(data);
    }

    private void ifLoginViewVisable() {
        //默认添加了headview，home，institute，如果添加我的收藏、我的动态则需要强力插入！！！
        int localChildViewSize = 4;
        if (mContext.getUserInformationManager().isLogin()) {
            this.removeView(myDyna);
            myDyna = LayoutInflater.from(getContext()).inflate(R.layout.view_left_sidebar_item, null);
            ((TextView) myDyna.findViewById(R.id.textViewSidebarItemTitle)).setText(R.string.my_dyna);
            ((ImageView) myDyna.findViewById(R.id.imageViewLeftSidebarItemAvatar)).setImageResource(R.drawable.icon_sidebar_dynamic_selector);
            myDyna.setTag(LOCAL_ITEM_TYPE_MYDYNA);
            myDyna.setOnClickListener(this);
            this.addView(myDyna, localChildViewSize);
        } else {
            this.removeView(myDyna);
        }
    }

    public void displaySources(ArrayList<HomeLeftSidebarFeed> sources) {
        checkData(sources);
    }

    private int currentGroupChildViewSize = 0;

    private void checkData(ArrayList<HomeLeftSidebarFeed> datas) {
        currentGroupChildViewSize = this.getChildCount();
        for (int i = datas.size() - 1; i >= 0; i--) {
            HomeLeftSidebarFeed homeLeftSidebarFeed = datas.get(i);
            View view = LayoutInflater.from(getContext()).inflate(R.layout.view_left_sidebar_item, null);
            TextView textViewSidebarItemTitle = (TextView) view.findViewById(R.id.textViewSidebarItemTitle);
            ImageView imageViewLeftSidebarAvatar = (ImageView) view.findViewById(R.id.imageViewLeftSidebarItemAvatar);

            imageViewLeftSidebarAvatar.setTag(homeLeftSidebarFeed);

            ImageUtil.getInstance().displayImage(homeLeftSidebarFeed.getImage(), imageViewLeftSidebarAvatar, this);

            textViewSidebarItemTitle.setText(homeLeftSidebarFeed.getTitle());
            view.setTag(NET_ITEM_TYPE);
            view.setTag(R.string.SIDE_BAR_ITEM_KEY, homeLeftSidebarFeed);
            view.setOnClickListener(this);
            // 此时viewgroup里已经有viewitem了，所以应该从groupSize开始添加下面的view。
            this.addView(view, currentGroupChildViewSize);
        }

        footView = LayoutInflater.from(getContext()).inflate(R.layout.view_left_sidebar_footview, null);
        textViewLeftSidebarSearch = (TextView) footView.findViewById(R.id.textViewLeftSidebarSearch);
        textViewLeftSidebarSettings = (TextView) footView.findViewById(R.id.textViewLeftSidebarSettings);
        textViewLeftSidebarAbout = (TextView) footView.findViewById(R.id.textViewLeftSidebarAbout);
        imageButtonLeftSidebarAboutSina = (ImageButton) footView.findViewById(R.id.imageButtonLeftSidebarAboutSina);
        textViewLeftSidebarSearch.setOnClickListener(this);
        textViewLeftSidebarSettings.setOnClickListener(this);
        textViewLeftSidebarAbout.setOnClickListener(this);
        imageButtonLeftSidebarAboutSina.setOnClickListener(this);
        this.addView(footView);
    }

    @Override
    public void onClick(View v) {
        if (v.getTag() != null) {
            int viewOnClickTag = (int) v.getTag();
            boolean isChange = true;
            switch (viewOnClickTag) {
                case LOCAL_ITEM_TYPE_HOME:
                    mContext.pushFragmentToBackStack(MainFragment.class, null);
                    BusProvider.getInstance().post(new MainFragment.DisplayFirstLabel());
                    break;
                case LOCAL_ITEM_TYPE_INSTITUTE:
                    mContext.pushFragmentToBackStack(MainFragment.class, null);
                    BusProvider.getInstance().post(new MainFragment.DisplaySecondLabel());
                    break;
                case LOCAL_ITEM_TYPE_MYFAVORITE:
                    if (!mContext.getUserInformationManager().isLogin()) {
                        Intent myFavIntent = new Intent();
                        myFavIntent.setClass(mContext, LoginActivity.class);
                        mContext.startActivity(myFavIntent);
                        isChange = false;
                    } else {
                        enterCategoryFragment(new CategoryFragment.CategoryDataObj().
                                setCategoryFragmetType(QDEnum.CategoryFragmentEnum.MYFAV)
                                .setTitleText(mContext.getString(R.string.my_favorite))
                                .setIsTitlebarLeftBtnVisiable(false));
                    }
                    break;
                case LOCAL_ITEM_TYPE_MYDYNA:
                    enterMyDynamicFragment();
                    break;
                default:
                    HomeLeftSidebarFeed homeLeftSidebarFeed = (HomeLeftSidebarFeed) v.getTag(R.string.SIDE_BAR_ITEM_KEY);
                    displayCategotyList(homeLeftSidebarFeed);
                    break;
            }
            if (isChange) {
                if (selectView != null) {
                    selectView.setSelected(false);
                }
                selectView = v;
                v.setSelected(true);
            }
        }

        int viewOnClickId = v.getId();
        switch (viewOnClickId) {
            case R.id.imageViewLeftSidebarAvatar:
            case R.id.textViewLeftSidebarUser:
            case R.id.textViewLeftSidebarUserDes:
                if (!mContext.getUserInformationManager().isLogin()) {
                    Intent intent = new Intent();
                    intent.setClass(mContext, LoginActivity.class);
                    mContext.startActivity(intent);
                } else {
                    enterPersonalCenterFragment();
                }
                break;
            case R.id.textViewLeftSidebarSearch: {
                Intent toSearch = new Intent(mContext, SearchActivity.class);
                toSearch.putExtra(QDBaseActivity.KEY_ActivityAnim, QDEnum.EActivityAnim.SlideFromBottom);
                mContext.startActivity(toSearch);
            }
            break;
            case R.id.textViewLeftSidebarSettings: {
                Intent toSet = new Intent(mContext, SettingActivity.class);
                toSet.putExtra(QDBaseActivity.KEY_ActivityAnim, QDEnum.EActivityAnim.SlideFromBottom);
                mContext.startActivity(toSet);
            }
            break;
            case R.id.textViewLeftSidebarAbout:
                Intent aboutIntent = new Intent(mContext, WebViewActivity.class);
                aboutIntent.putExtra(WebViewActivity.EXTRA_WEBVIEW_URL, Constants.ABOUT);
                aboutIntent.putExtra(WebViewActivity.EXTRA_WEBVIEW_TITLE, getContext().getText(R.string.about_me));
                aboutIntent.putExtra(QDBaseActivity.KEY_ActivityAnim, QDEnum.EActivityAnim.SlideFromBottom);
                mContext.startActivity(aboutIntent);
                break;
            case R.id.imageButtonLeftSidebarAboutSina:
                Intent aboutSina = new Intent(mContext, WebViewActivity.class);
                aboutSina.putExtra(WebViewActivity.EXTRA_WEBVIEW_URL, Constants.WEIBO);
                aboutSina.putExtra(WebViewActivity.EXTRA_WEBVIEW_TITLE, getContext().getText(R.string.follow_us));
                aboutSina.putExtra(QDBaseActivity.KEY_ActivityAnim, QDEnum.EActivityAnim.SlideFromBottom);
                mContext.startActivity(aboutSina);
                break;
        }

        mContext.closeDrawers();
    }

    private void displayCategotyList(HomeLeftSidebarFeed homeLeftSidebarFeed) {
        CategoryFragment.CategoryDataObj categoryDataObj = new CategoryFragment.CategoryDataObj().
                setCategoryFragmetType(QDEnum.CategoryFragmentEnum.CATEGORY)
                .setCategoryId(homeLeftSidebarFeed.getId())
                .setIsTitlebarLeftBtnVisiable(false)
                .setTitleText(homeLeftSidebarFeed.getTitle());
        enterCategoryFragment(categoryDataObj);
    }

    //如果登陆成功了，下次直接读取。
    private void readCacheDisplayUserInfo(UserInformation userInformation) {
        if (!TextUtils.isEmpty(userInformation.getUserIcon())) {
            ImageUtil.getInstance().displayRoundedImage(userInformation.getUserIcon(), imageViewLeftSidebarAvatar);
        } else {
            imageViewLeftSidebarAvatar.setImageResource(R.drawable.icon_default_avatar);
        }

        if (mContext.getUserInformationManager().isLogin()) {
            String name = userInformation.getUserName();
            textViewLeftSidebarUser.setTextColor(mContext.getResources().getColor(R.color.white));
            textViewLeftSidebarUser.setText(name);

            textViewLeftSidebarUserDes.setVisibility(View.VISIBLE);
            textViewLeftSidebarUserDes.setText(userInformation.getUserDescription());
        } else {
            textViewLeftSidebarUser.setTextColor(mContext.getResources().getColor(R.color.golden));
            textViewLeftSidebarUser.setText(mContext.getString(R.string.left_sidebar));
            textViewLeftSidebarUserDes.setVisibility(View.GONE);
        }

        ifLoginViewVisable();
    }

    public void onUpdateUserInfo(UserInformation userInformation) {
        readCacheDisplayUserInfo(userInformation);
    }

    public void logoutUpdateUi() {
        readCacheDisplayUserInfo(mContext.getUserInformationManager().getUserInformation());
    }

    public void onLoadingStarted(String imageUri, View view) {

    }

    /**
     * Is called when an error was occurred during image loading
     *
     * @param imageUri   Loading image URI
     * @param view       View for image. Can be <b>null</b>.
     * @param failReason {@linkplain com.nostra13.universalimageloader.core.assist.FailReason The reason} why image
     *                   loading was failed
     */
    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

    }

    /**
     * Is called when image is loaded successfully (and displayed in View if one was specified)
     *
     * @param imageUri    Loaded image URI
     * @param view        View for image. Can be <b>null</b>.
     * @param loadedImage Bitmap of loaded and decoded image
     */
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        if (loadedImage == null)
            return;
        HomeLeftSidebarFeed homeLeftSidebarFeed = (HomeLeftSidebarFeed) view.getTag();
        if (homeLeftSidebarFeed == null) {
            ((ImageView) view).setImageBitmap(loadedImage);
        } else {
            ImageView imageView = (ImageView) view;
            StateListDrawable stalistDrawable = null;
            Drawable drawable = imageView.getBackground();
            if (drawable instanceof StateListDrawable) {
                stalistDrawable = (StateListDrawable) drawable;
            }
            if (stalistDrawable == null) {
                stalistDrawable = new StateListDrawable();
            }
            Drawable drawable1 = new BitmapDrawable(mContext.getResources(), loadedImage);
            if (imageUri.equals(homeLeftSidebarFeed.getImage())) {
                viewDrawableSelect.put(homeLeftSidebarFeed.getImage(), drawable1);
                stalistDrawable.addState(View.EMPTY_STATE_SET, drawable1);
                ImageUtil.getInstance().displayImage(homeLeftSidebarFeed.getImage_highlighted(), imageView, this);

            } else if (imageUri.equals(homeLeftSidebarFeed.getImage_highlighted())) {
                stalistDrawable.addState(View.PRESSED_ENABLED_STATE_SET, drawable1);
                stalistDrawable.addState(View.ENABLED_FOCUSED_STATE_SET, drawable1);
                stalistDrawable.addState(View.FOCUSED_STATE_SET, drawable1);
                stalistDrawable.addState(View.SELECTED_STATE_SET, drawable1);
                Drawable drawable2 = viewDrawableSelect.get(homeLeftSidebarFeed.getImage());
                if (drawable2 != null) {
                    stalistDrawable.addState(View.ENABLED_STATE_SET, drawable2);
                    stalistDrawable.addState(View.EMPTY_STATE_SET, drawable2);
                }
            }
            imageView.setImageDrawable(stalistDrawable);
        }
    }

    public void onLoadingCancelled(String imageUri, View view) {
    }

    @Subscribe
    public void receiveUserUpdate(UserInformation userInformation) {
        readCacheDisplayUserInfo(userInformation);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        BusProvider.getInstance().register(this);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        BusProvider.getInstance().unregister(this);
    }

    private void enterCategoryFragment(CategoryFragment.CategoryDataObj categoryDataObj) {
        mContext.pushFragmentToBackStack(CategoryFragment.class, categoryDataObj);
    }

    private void enterMyDynamicFragment() {
        mContext.pushFragmentToBackStack(MyDynamicFragment.class, null);
    }

    private void enterPersonalCenterFragment() {
        mContext.pushFragmentToBackStack(PersonalCenterFragment.class, null);
    }

    @Subscribe
    public void receiveMainFragmentChange(MainFragment.MainFragmentChange event)
    {
        if (selectView != null)
        {
            selectView.setSelected(false);
        }
        if (event.getI() == 0)
        {
            homePage.setSelected(true);
            selectView = homePage;
        }
        else
        {
            institute.setSelected(true);
            selectView = institute;
        }
    }

}
